﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using System.IO;
using System.Linq;
using Excel;
using System.Data;
using QFramework;

public interface IHK_QuesDataSystem : ISystem
{
    /// <summary>
    /// 通过 Json 文件，读取题库数据，可通过URL或者路径读取
    /// </summary>
    void GetQuesDataFromJson(string filePath);

    /// <summary>
    /// 通过 Excel 文件，读取题库数据（仅限PC端使用）
    /// </summary>
    void GetQuesDataFromExcel(string filePath);
}

public class HK_QuesDataSystem : AbstractSystem, IHK_QuesDataSystem
{
    DataReader dataReader;

    protected override void OnInit()
    {
        if (dataReader == null)
            dataReader = new GameObject().AddComponent<DataReader>();
    }

    /// <summary>
    /// 通过 Excel 文件，读取题库数据（仅限PC端使用）
    /// </summary>
    public void GetQuesDataFromExcel(string filePath)
    {
        HK_QuizData quesDataList = new HK_QuizData();

        using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.Read))
        {
            IExcelDataReader reader = ExcelReaderFactory.CreateOpenXmlReader(fileStream);

            // 表格数据所有读取到result里
            DataSet result = reader.AsDataSet();

            int columns = result.Tables[0].Columns.Count;
            int rows = result.Tables[0].Rows.Count;

            DataTable score_Table = result.Tables[0];
            DataTable singleChoice_Table = result.Tables[1];
            DataTable multipleChoice_Table = result.Tables[2];
            DataTable trueFalse_Table = result.Tables[3];
            DataTable blank_Table = result.Tables[4];
            DataTable shortAnswer_Table = result.Tables[5];

            // 获取 分数Table上的数据
            quesDataList.SingleChoice_Score = Convert.ToInt32(score_Table.Rows[1][1].ToString());
            quesDataList.MultipleChoice_Score = Convert.ToInt32(score_Table.Rows[2][1].ToString());
            quesDataList.TrueFalse_Score = Convert.ToInt32(score_Table.Rows[3][1].ToString());
            quesDataList.Blank_Score = Convert.ToInt32(score_Table.Rows[4][1].ToString());
            quesDataList.ShortAnswer_Score = Convert.ToInt32(score_Table.Rows[5][1].ToString());

            // 获取 单选题Table上的数据
            int row_SingleChoice = singleChoice_Table.Rows.Count;
            quesDataList.SingleChoice_List = new List<HK_SingleChoiceData>();
            for (int i = 1; i < row_SingleChoice; i++)
            {
                // 如果这一行开头为空，则跳过这一行
                if (string.IsNullOrEmpty(singleChoice_Table.Rows[i][0].ToString()))
                    continue;

                HK_SingleChoiceData singleChoice = new HK_SingleChoiceData();
                singleChoice.QuesName = singleChoice_Table.Rows[i][0].ToString();
                singleChoice.Options = new string[4];
                singleChoice.Options[0] = singleChoice_Table.Rows[i][1].ToString();
                singleChoice.Options[1] = singleChoice_Table.Rows[i][2].ToString();
                singleChoice.Options[2] = singleChoice_Table.Rows[i][3].ToString();
                singleChoice.Options[3] = singleChoice_Table.Rows[i][4].ToString();
                singleChoice.Answer = singleChoice_Table.Rows[i][5].ToString();
                singleChoice.Analysis = singleChoice_Table.Rows[i][6].ToString();

                quesDataList.SingleChoice_List.Add(singleChoice);
            }

            // 获取 多选题Table上的数据
            int row_MultipleChoice = multipleChoice_Table.Rows.Count;
            quesDataList.MultipleChoice_List = new List<HK_MultipleChoiceData>();
            for (int i = 1; i < row_MultipleChoice; i++)
            {
                // 如果这一行开头为空，则跳过这一行
                if (string.IsNullOrEmpty(multipleChoice_Table.Rows[i][0].ToString()))
                    continue;

                HK_MultipleChoiceData multipleChoice = new HK_MultipleChoiceData();
                multipleChoice.QuesName = multipleChoice_Table.Rows[i][0].ToString();
                multipleChoice.Options = new string[4];
                multipleChoice.Options[0] = multipleChoice_Table.Rows[i][1].ToString();
                multipleChoice.Options[1] = multipleChoice_Table.Rows[i][2].ToString();
                multipleChoice.Options[2] = multipleChoice_Table.Rows[i][3].ToString();
                multipleChoice.Options[3] = multipleChoice_Table.Rows[i][4].ToString();
                multipleChoice.Answer = multipleChoice_Table.Rows[i][5].ToString();
                multipleChoice.Analysis = multipleChoice_Table.Rows[i][6].ToString();

                quesDataList.MultipleChoice_List.Add(multipleChoice);
            }

            // 获取 判断题Table上的数据
            int row_TrueFalse = trueFalse_Table.Rows.Count;
            quesDataList.TrueFalse_List = new List<HK_TrueFalseData>();
            for (int i = 1; i < row_TrueFalse; i++)
            {
                // 如果这一行开头为空，则跳过这一行
                if (string.IsNullOrEmpty(trueFalse_Table.Rows[i][0].ToString()))
                    continue;

                HK_TrueFalseData trueFalse = new HK_TrueFalseData();
                trueFalse.QuesName = trueFalse_Table.Rows[i][0].ToString();
                trueFalse.AnswerID = Convert.ToInt32(trueFalse_Table.Rows[i][1].ToString());
                trueFalse.Analysis = trueFalse_Table.Rows[i][2].ToString();

                quesDataList.TrueFalse_List.Add(trueFalse);
            }

            // 获取 填空题Table上的数据
            int row_Blank = blank_Table.Rows.Count;
            quesDataList.Blank_List = new List<HK_BlankData>();
            for (int i = 1; i < row_Blank; i++)
            {
                // 如果这一行开头为空，则跳过这一行
                if (string.IsNullOrEmpty(blank_Table.Rows[i][0].ToString()))
                    continue;

                HK_BlankData blank = new HK_BlankData();
                blank.QuesName = blank_Table.Rows[i][0].ToString();
                blank.Answer_List = blank_Table.Rows[i][1].ToString().Split('|').ToList();
                blank.Analysis = blank_Table.Rows[i][2].ToString();

                quesDataList.Blank_List.Add(blank);
            }

            //获取 简答题Table上的数据
            int row_ShortAnswer = shortAnswer_Table.Rows.Count;
            quesDataList.ShortAnswer_List = new List<HK_ShortAnswerData>();
            for (int i = 1; i < row_ShortAnswer; i++)
            {
                // 如果这一行开头为空，则跳过这一行
                if (string.IsNullOrEmpty(shortAnswer_Table.Rows[i][0].ToString()))
                    continue;

                HK_ShortAnswerData shortAnswer = new HK_ShortAnswerData();
                shortAnswer.QuesName = shortAnswer_Table.Rows[i][0].ToString();
                shortAnswer.Answer = shortAnswer_Table.Rows[i][1].ToString();
                shortAnswer.Analysis = shortAnswer_Table.Rows[i][2].ToString();

                quesDataList.ShortAnswer_List.Add(shortAnswer);
            }
        }

        ProcessQuesData(quesDataList);
    }

    /// <summary>
    /// 通过 Json 文件，读取题库数据，可通过URL或者路径读取
    /// </summary>
    public void GetQuesDataFromJson(string filePath)
    {
        dataReader.GetQuesData(filePath, ProcessQuesData);
    }

    // 通过协程获取 Json 数据
    public class DataReader : MonoBehaviour
    {
        public void GetQuesData(string filePath, Action<HK_QuizData> callback)
        {
            StartCoroutine(GetQuesData_IE(filePath, callback));
        }

        IEnumerator GetQuesData_IE(string filePath, Action<HK_QuizData> callback)
        {
            UnityWebRequest request = UnityWebRequest.Get(filePath);
            yield return request.SendWebRequest();

            Debug.Log(request.downloadHandler.text);

            HK_QuizData quizDataList = JsonUtility.FromJson<HK_QuizData>(request.downloadHandler.text);

            callback(quizDataList);
        }
    }

    // 数据获取后进行数据存储
    void ProcessQuesData(HK_QuizData quesDataList)
    {
        IHK_QuesDataModel quizDataModel = this.GetModel<IHK_QuesDataModel>();
        quizDataModel.QuizData.Value = quesDataList;

        quizDataModel.Single_Num.Value = quesDataList.SingleChoice_List.Count;
        quizDataModel.Multiple_Num.Value = quesDataList.MultipleChoice_List.Count;
        quizDataModel.TrueFalse_Num.Value = quesDataList.TrueFalse_List.Count;
        quizDataModel.Blank_Num.Value = quesDataList.Blank_List.Count;
        quizDataModel.ShortAnswer_Num.Value = quesDataList.ShortAnswer_List.Count;

        quizDataModel.TotalScore.Value = quesDataList.SingleChoice_Score * quesDataList.SingleChoice_List.Count
            + quesDataList.MultipleChoice_Score * quesDataList.MultipleChoice_List.Count
            + quesDataList.TrueFalse_Score * quesDataList.TrueFalse_List.Count
            + quesDataList.Blank_Score * quesDataList.Blank_List.Count
            + quesDataList.ShortAnswer_Score * quesDataList.ShortAnswer_List.Count;

        Debug.Log("单选题共：" + quesDataList.SingleChoice_List.Count);
        Debug.Log("多选题共：" + quesDataList.MultipleChoice_List.Count);
        Debug.Log("判断题共：" + quesDataList.TrueFalse_List.Count);
        Debug.Log("填空题共：" + quesDataList.Blank_List.Count);
        Debug.Log("简答题共：" + quesDataList.ShortAnswer_List.Count);

        this.SendEvent<HK_InitQuesItems_Event>();
    }
}
